package com.example.java.kafka.producer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

public class CustomProducerCallback {
    public static void main(String[] args) throws InterruptedException {
        // 创建 kafka 生产者的配置对象
        KafkaProducer<String, String> kafkaProducer = CustomProducerCallback.getKafkaProducer();
        // 调用 send 方法发送消息
        for (int i = 0; i < 5; i++) {
            // 该方法在 Producer 收到 ack 时调用，为异步调用
            kafkaProducer.send(new ProducerRecord<>("producer1", "ni hao, i am producer1, send message " + i), (metadata, exception) -> {
                if (exception == null) {
                    // 没有异常,输出信息到控制台
                    System.out.println("消息发往主题：" + metadata.topic() + "->" + "分区：" + metadata.partition());
                } else {
                    // 出现异常打印
                    exception.printStackTrace();
                }
            });
            // 延迟一会会看到数据发往不同分区
            Thread.sleep(2);
        }
        // 关闭资源
        kafkaProducer.close();
        System.out.println("CustomProducerCallback executed successfully");
    }

    private static KafkaProducer<String, String> getKafkaProducer() {
        Properties properties = new Properties();
        // 给 kafka 配置对象添加配置信息：bootstrap.servers
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "43.139.50.31:9092");
        // key,value 序列化（必须）：key.serializer，value.serializer
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        // 创建 kafka 生产者对象
        return new KafkaProducer<>(properties);
    }
}